var express = require('express');
var router = express.Router();
var authList = require('../../../database/model/authControl/authControl')
let queryFilter=({dictKey,label,rangeTime,userId,ownSystem})=>{
  let queryFilterOjb={//构建动态查询对象
    $and: [
      {
        $or:[
        {userId:userId},
      ]
    }]
  }
   if (dictKey && dictKey.length != 0) {
     queryFilterOjb.$and.push({ dictKey: { $in: dictKey } })
   }
   if (label && label.length != 0) {//this指向查询的model表对应的label
     queryFilterOjb.$and.push({ $where:`this.label.indexOf('${label}')> -1`})
   } 
   if (rangeTime && rangeTime.length != 0 && rangeTime[0].length != 0 && rangeTime[1].length != 0) {
     queryFilterOjb.$and.push({
       $and: [
         {
           createdTime: { $gte:rangeTime[0]}
         },
         {
           createdTime: { $lt:rangeTime[1]}
         }
       ]
     })
   }
   if (queryFilterOjb.$and.length == 0) {
     queryFilterOjb = {}
   }
   return queryFilterOjb
}

router.post('/authList', async(req, res) => {
  let { dictKey, label, rangeTime, pageNo = 1, pageSize = 10,userId} = req.body
  let filterObj=queryFilter({dictKey,label,rangeTime,pageNo,pageSize,userId})
  const query = authList.find(filterObj)//定义一次查询表示查询一次 第一次查询符合的数量
  const query2 = authList.find(filterObj)//第二次查询直接分页下发数据 或者在第一次查询后面继续find（）
  //count ({})方法已弃用。如果要计算集合中的文档数 (例如count ({})), 请改用estimatedDocumentCount() 函数。否则, 请改用countDocuments()函数。
  const total = await query
  const data= await query2.limit(pageSize).skip((pageNo - 1) * pageSize)|| []
  if (total || data.length > 0) {
    res.send({
      code: 1,
      msg: "查询成功",
      pageNo: pageNo,
      pageSize: pageSize,
      total: total.length,
      data: data
    })
  } else {
    res.send({
      code: 1,
      msg: "查询失败"+JSON.stringify(data),
    })
  }
})
router.post('/allAuthList', async(req, res) => {
  let {userId} = req.body
  let queryFilterOjb={//构建动态查询对象
    $and: [
      {
        $or:[
        {userId:userId},
        {userId:'0'}
      ]
    }]
  }
  const deleteKey={_id:0,__v:0}
  authList.find(queryFilterOjb,deleteKey).then(data=>{
    res.send({
      code: 1,
      data:data,
      msg: '查询全部路由成功'
    })
  })
}),
router.post('/auth/isAlreadyExists',(req,res)=>{
  let {userId,label,value} =req.body
  const filter={
    $and:[
      {userId:userId},
      {label:label}
    ]
  }
  authList.find(filter).then((data)=>{
    console.log(data,789)
    if(data&&data.length>0){
      res.send({
        msg:"该路由已存在",
        code:0
      })
    }else{
      res.send({
        msg:"该路由不存在,可以新增",
        code:1
      })
    }
  })
})
router.post("/auth/authDetail",(req,res)=>{
  let {id}=req.body
  authList.findById(id).then((data,err)=>{
    console.log(err,data,789)
    res.send({
      msg:"查询详情成功",
      code:1,
      data:data
    })
  })
})
router.delete("/auth/authList",(req,res)=>{
  let {idList}=req.body
  const filter={
    _id:{
      $in:idList
    }
  }
  authList.deleteMany(filter).then((data,err)=>{
    console.log(err,data,789)
    res.send({
      msg:"删除成功",
      code:1,
      data:data
    })
  })
})
router.post('/auth/addOrUpdateAuth',async (req,res)=>{
  let {userId,label,value,id} =req.body
  const filter={
    $and:[
      {userId:userId},
      {label:label}
    ]
  }
  const update={
    $set:{
      value:value
    }
  }
  let msg="新增成功"
  const option={upsert:true,setDefaultsOnInsert:true}
  let bool=false
  if(id){
    filter.$and.push({_id:id})
    msg="修改成功"
  }else{
   await authList.find(filter).then((data)=>{
      if(data&&data.length>0){
        res.send({
          msg:"新增失败，该路由已存在",
          code:0
        })
        bool=true
      }
    })
    if(bool){
      return 
    }
  }
  authList.updateOne(filter,update,option).then((data,err)=>{
    res.send({
      msg:msg,
      code:1
    })
  })
})
module.exports = router
